<?php
/**
 * Created by IntelliJ IDEA.
 * User: TinND
 * Date: 4/3/14
 * Time: 1:57 PM
 */
header('Content-type: application/json');
$data = json_decode(file_get_contents("php://input"));
$api = $data->api;
$id = $data->id;
$type = $data->type;
if (isset($api) && isset($id)) {
//    switch($api){
//        case 2230: break;
//    }
    $tempPath = $_FILES['file']['tmp_name'];
    list($hostPath) = explode($_SERVER['DOCUMENT_ROOT'], dirname(__FILE__));
    $rootPath = $hostPath . $_SERVER['DOCUMENT_ROOT'] . '/';

    if (isset($type)) {
        $productPath = $rootPath . 'img/product/' . $id . '/' . $type . '/';
        $files = glob($productPath . '*'); // get all file names
        foreach ($files as $file) {
            if (is_file($file)) unlink($file); // delete file
        }
    } else {
        $productPath = $rootPath . 'img/product/' . $id . '/';
        function rrmdir($dir) {
            if (is_dir($dir)) {
                $objects = scandir($dir);
                foreach ($objects as $object) {
                    if ($object != "." && $object != "..") {
                        if (filetype($dir . "/" . $object) == "dir")
                            rrmdir($dir . "/" . $object);
                        else unlink($dir . "/" . $object);
                    }
                }
                reset($objects);
                rmdir($dir);
            }
        }

        rrmdir($productPath);
    }

    $answer = array('success' => true,
        'message' => 'Delete success ' . $productPath);
    echo json_encode($answer);
} else {
    echo json_encode(array('success' => false, 'message' => 'Please input: API - ID - TYPE'));
}